package com.taplinker.app;

import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.taplinker.client.R;
import com.taplinker.client.core.LoginHistoryManager;
import com.taplinker.client.domain.LoginUser;

public class LoginHistoryAdapter extends BaseAdapter {
	private Context context;
	private List<LoginUser> userList;
	private Handler handler;

	public LoginHistoryAdapter(Context context, List<LoginUser> users, Handler handler) {
		this.context = context;
		this.userList = users;
		this.handler = handler;
	}

	@Override
	public int getCount() {
		return userList.size();
	}

	@Override
	public Object getItem(int position) {
		return userList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.login_history_lv_item, null);
			holder.name = (TextView) convertView.findViewById(R.id.name_tv);
			holder.delete = convertView.findViewById(R.id.delete_iv);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		final LoginUser user = userList.get(position);
		holder.name.setText(user.getName());
		holder.delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				userList.remove(position);
				notifyDataSetChanged();
				LoginHistoryManager.getInstance().delete(context, user);
				Message msg = new Message();
				msg.obj = user.getName();
				handler.sendMessage(msg);
			}
		});
		return convertView;
	}

	class ViewHolder {
		public TextView name;
		public View delete;
	}

}
